
from ui.linepicker import pick
from ui.input import ninput

from src.vobjects.playlist import Playlist
from src.vobjects.torrent import Torrent
from src.vobjects.channel import Channel
from src.vobjects.player import Player
from src.vobjects.video import Video
from src.vobjects.item import Item
from src.config import Config
from src.api import Api

class RoseNG:

    def __init__(self):
        self.config = Config()
        self.api = Api(self.config)
        self.player = Player(api=self.api)

        self.app_title = "RoseNG"
     
    def display_video_menu(self):
        if not self.config.ShowVideoMenu: return "VA"

        items = [
            Item(title="Video and Audio", parent="VA"),
            Item(title="Only video",      parent="V"),
            Item(title="Only audio",      parent="A"),
            Item(title="Download",        parent="DW"),
        ]
        
        item, index = pick(self.app_title, items)
        if index == -1: return

        if type(item) is list: item = item[0]

        return item.parent

    def play_video(self, video):
        play_option = self.display_video_menu()
        self.player.play(video.url, play_option=play_option, video=video)

    def display_playlist(self, parent, playlist, index=0):
        items = list()
        for pvideo in playlist.videos:
            items.append(pvideo.to_item())

        item, index = pick(f"{parent.title}", items)
        if index == -1: self.display_plugin(parent, parent.items)

        self.play_video(item.parent)

        self.display_playlist(parent, playlist, index)


    def display_plugin(self, plugin_item, items=None, index=0):
        if items == None:
            plugin_params = plugin_item.parent.params
            if 'query' in plugin_params:
                query = ninput(title="Write your query: ", length=50, app_title="RoseNG: " + plugin_item.title, description=plugin_item.parent.query_description)
            else: query = ""

            params = {
                'query' : query, 
            }
            items = self.api.get_plugin_items(plugin_item.parent.id, params=params)

        item, index = pick(f"{plugin_item.title}", items)
        if index == -1: self.display_menu()

        plugin_item.items = items

        if type(item.parent) == Video:
            self.play_video(item.parent)
        elif type(item.parent) == Channel:
            self.display_playlist(plugin_item, item.parent)
        elif type(item.parent) == Playlist: 
            self.display_playlist(plugin_item, item.parent)
        elif type(item.parent) == Torrent:
            item.parent.play()

        self.display_plugin(plugin_item, items)


    def display_menu(self, index=0):
        plugins = self.api.get_plugins()

        items = list()
        for plugin in plugins:
            items.append(plugin.to_item())

        item, index = pick(self.app_title, items)
        if index == -1: exit(0)

        self.display_plugin(item)



